import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

let loadDialog
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 120000, // request timeout
  // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`)，promise 将被 resolve; 否则，promise 将被 rejected
  validateStatus: function(status) {
    return status >= 200 && status < 500 // 默认的
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // 请求开始加载loading框,防止重复提交接口@2020-06-18
    loadDialog = Loading.service({
      fullscreen: true,
      lock: true,
      background: 'rgba(0, 0, 0, 0)'  //rgba(0, 0, 0, 0.7)
    })
    // end
    // do something before request is sent
    config.headers['Content-Type'] = 'application/json'

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // 关闭 loadDialog
    if (loadDialog) {
      loadDialog.close()
    }
    // end
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 关闭 loadDialog
    if (loadDialog) {
      loadDialog.close()
    }
    // end
    const res = response.data // 对应xjgj后端项目的RestResponse类
    // if the custom code is not 20000, it is judged as an error.
    if (res.status !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 9999: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.status === 403) {
        // to re-login
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    // 关闭 loadDialog
    if (loadDialog) {
      loadDialog.close()
    }
    // end
    console.error('[err print by yxy]', error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
